// pages/order_refund_detail/index.js
import {
    getNavigationbar
} from "../../api/index.js"
import {
    ReIndex
} from "../../api/order.js"
Page({
    options: {
        styleIsolation: "shared"
    },
    /**
     * 页面的初始数据
     */

    data: {
        sohian: false,
        refundDetails: {},
        active: 1, //当前的步数
        steps: [{
                status: 1,
                text: '提交申请',
            },
            {
                status: 1,
                text: '商家处理',
            },
            {
                status: 2,
                text: '退款成功',
            },
        ],

        Returnssteps: [{
                status: 0,
                text: '提交申请',
            },
            {
                status: 1,
                text: '商家处理',
            },
            {
                status: 2,
                text: '买家发货',
            },
            {
                status: 2,
                text: '填快递单',
            },
            {
                status: 3,
                text: '商家收货',
            },
            {
                status: 4,
                text: '完成',
            },
        ],
        refundState: true,
        sohwMian: false,
        dataobj: {},
        detailsobj: {},
        goodsList: [{
            goodsImg: "/images/element_christmas_xpzq@2x.png",
            goodsName: "商品名称商品名称商品名称商品名称商品名称商品名称商品名称商品名称商品名称",
            goodsPrice: "310.00",
            goodsSpecs: "规格规格规格个规格规格规格规格规格规格个规格规格规格",
            goodsSpecsCount: 2
        }],
        btnList: [

            {
                text: "撤销申诉",
                type: "editappeal"
            },
        ]
    },
    previewSqs(event) {
        console.log('event', event)
        // 拿到图片的地址url
        let currentUrl = event.currentTarget.dataset.src;
        // 微信预览图片的方法
        wx.previewImage({
            current: currentUrl, // 图片的地址url
            urls: this.data.refundDetails.img // 预览的地址url
        })
    },

    /**
     * 返回上一页
     */
    onClickLeft() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; // 获取上一页页面实例
        // const objData = options.obj; // 获取传递过来的记录信息
        // // 在上一页页面中处理记录信息
        // prevPage.setData({
        //     recordedData: objData
        // });
    },

    /**
     * 复制退款编号回调函数方法
     * @param {*} e 
     */
    handleCopy(e) {
        console.log('复制退款编号');
        wx.setClipboardData({
            data: e.currentTarget.dataset.value,
            success: function (res) {
                // wx.getClipboardData({
                //     success: function (res) {
                //         console.log(res.data); // 输出：'要复制的内容'
                //     }
                // });
            }
        });
    },
    formatDateTime(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();
        const formattedDateTime = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
        return formattedDateTime;
    },
    // 退款详情


    getAfterSales(val) {
        this.data.btnList = []
        ReIndex({
            act: 'server_config',
        }).then(resj => {
            console.log('时间剩余', resj, resj.server_time);

            getNavigationbar({
                act: 'order_refund_detail',
                id: val.id || ''
            }).then(res => {
                // if (res.refundtype != 1 && res.order_state == 0) {
                    if (res.order_state == 0 || res.order_state == '0') {
                    this.setData({
                        steps: this.data.Returnssteps
                    });
                }
                console.log('详情', res)
                const timestamp = res.inputtime;
                const updatetamp = res.updatetime;
                const date = new Date(timestamp * 1000);
                const updatdate = new Date(updatetamp * 1000);

                let systemTime = 1710209805; // 假设系统时间为1710127152
                let days = 3; // 假设需要增加3天
                let countdown = this.countdownTime(systemTime, days);
                let data = this.getRefundStatus(parseInt(res.isclose), parseInt(res.status), parseInt(res.isinter), parseInt(res.refundtype), res)
                console.log('---------------------------', data)


                if (data.statusBlock[0] == 2 && data.descTime == '审核通过：正等待退款') {
                    data.statusBlock = [2, data.descTime];
                    this.data.sohwMian = false
                }
               
                if (data.statusBlock[0] == 21 || data.statusBlock[0] == 2 || data.statusBlock[0] == 5) {

                } else {
                    this.data.sohwMian = true
                }
                if (data.statusBlock[0] == 21 && data.statusBlock[1] == '买家申请小二介入') {
                    this.data.sohwMian = false
                }
                if (data.statusBlock[0] == 1) {
                    let timeStr = ''
                    data.statusBlock[1] = '商家审核不通过'
                    // data.descTime = '请于6天2时38分内修改申请或申诉，超时自动取消'
                    timeStr = this.countdownTime(res.updatetime, 7);
                    // 商家审核不通过："原因 " + res.verify_error +
                    data.descTime = "请于" + timeStr + "内修改申请，超时自动取消";
                    res.verify_error = "原因：" + res.verify_error;
                    this.setData({
                        sohian: true
                    })
                }
                if(data.statusBlock[0] == 0 && data.statusBlock[1] == '商家处理') {
                    this.setData({
                        sohian: false
                    })
                }
                if (data.statusBlock[0] == 4) {
                    let timeStr = ''
                    data.statusBlock[1] = '商家审核不通过'
                    timeStr = this.countdownTime(res.updatetime, 3);
                    data.descTime = "请于" + timeStr + "内发货并填写/修改快递单或申诉";
                    data.verify_error = "原因：" + res.reciever_error;
                    res.verify_error = data.verify_error
                }
                if (data.statusBlock[0] == 20) {
                    // this.data.sohwMian = false
                }
                // if(data.statusBlock[0] == 7) {
                //     res.dateTime = res.updatdateTime
                // } else {

                // }
                res.dateTime = this.formatDateTime(date);
                res.countdown = countdown;
                res.descTime = data.descTime;
                res.RefundStatus = data.statusBlock;
                console.log('sohwMian', this.data.sohwMian)

                res.updatdateTime = this.formatDateTime(updatdate);
                let Array = []
                if (res.vouchimgs != '') {
                    const imgStr = res.vouchimgs;
                    const imgArray = imgStr.split("|").map(img => {
                        if (!img.startsWith("http://static.chonglaoban.cn/")) {
                            return img;
                        } else {
                            // 添加特定字符
                            return img;
                        }
                    });
                    Array = imgArray.map(img => {
                        if (!img.includes("http://static.chonglaoban.cn/")) {
                            return "http://static.chonglaoban.cn/" + img;
                        } else {
                            return img;
                        }
                    });
                } else {

                }
                console.log('imgArray', Array)
                this.data.detailsobj = res

                const systemTimestamp = resj.server_time; // 系统时间戳

                const updateTimestamp = parseInt(res.updatetime); // 更新时间戳
                const comparisonResult = this.calculateTimeDifference(systemTimestamp, updateTimestamp);
                console.log('倒计时', comparisonResult);
                res.comparisonResult = comparisonResult + '后自动处理'

                this.setData({
                    refundDetails: res,
                    steps: this.data.steps,
                    btnList: this.data.btnList,
                    sohwMian: this.data.sohwMian,
                    'refundDetails.img': Array
                });
            });
        })

    },
    getTiem(updateTimestamp) {
        // 原始时间戳（秒级）  
        let originalTimestamp = updateTimestamp;

        // 将秒级时间戳转换为毫秒级时间戳  
        let originalTimestampMilliseconds = originalTimestamp * 1000;

        // 一天的毫秒数  
        let oneDayInMilliseconds = 24 * 60 * 60 * 1000;

        // 三天的毫秒数  
        let threeDaysInMilliseconds = oneDayInMilliseconds * 3;

        // 计算三天后的时间戳（毫秒级）  
        let timestampAfterThreeDays = originalTimestampMilliseconds + threeDaysInMilliseconds;

        // 如果需要，可以将毫秒级时间戳转换回秒级时间戳  
        let timestampAfterThreeDaysInSeconds = Math.floor(timestampAfterThreeDays / 1000);
        return timestampAfterThreeDaysInSeconds
        // 输出结果  
        console.log('三天后的时间戳（毫秒级）：', timestampAfterThreeDays);
        console.log('三天后的时间戳（秒级）：', timestampAfterThreeDaysInSeconds);
    },
    calculateTimeDifference(systemTimestamp, updateTimestamp) {
        console.log('时间-------------', systemTimestamp, updateTimestamp)
        const timeDiff = this.getTiem(updateTimestamp) - systemTimestamp; // 计算时间差
        console.log('---------------', timeDiff)
        const days = Math.floor(timeDiff / (3 * 24 * 60 * 60)); // 计算天数
        const hours = Math.floor((timeDiff % (24 * 60 * 60)) / 3600); // 计算小时数
        const minutes = Math.floor((timeDiff % 3600) / 60); // 计算分钟数

        const cmps = {
            day: days,
            hour: hours,
            minute: minutes
        };

        if (cmps.day != null && cmps.day > 0) {
            return `${cmps.day}天${cmps.hour ?? 0}时${cmps.minute ?? 0}分`;
        } else if (cmps.hour != null && cmps.hour > 0) {
            return `${cmps.hour}时${cmps.minute ?? 0}分`;
        } else if (cmps.minute != null && cmps.minute > 0) {
            return `${cmps.minute}分`;
        } else {
            return "0";
        }
    },
    // 根据提供的判断条件添加退款状态字段
    getRefundStatus(isClose, status, isInter, refundtype, res) {
        console.log('进来啦', isClose, status, isInter)
        let statusBlock = [-1, ""];
        let buyerShippedIndex
        this.data.btnList = []
        if (isClose == 1) {
            if (status == 6) {
                statusBlock = [6, "已退款"];
            } else if (status == 7) {
                statusBlock = [7, "退款已关闭"];
            } else {
                statusBlock = [20, "退款已关闭"];
            }
        } else {
            switch (status) {
                case 0:
                    statusBlock = [0, "商家处理"];

                    buyerShippedIndex = this.data.steps.findIndex(element => element.text === '商家处理');
                    console.log('buyerShippedIndex', buyerShippedIndex)

                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    }, {
                        text: "撤销申请",
                        type: "remove"
                    }, {
                        text: "修改申请",
                        type: "edit"
                    })
                    if (buyerShippedIndex !== -1) {
                        this.data.steps.forEach((element, index) => {
                            if (index <= buyerShippedIndex) {
                                element.status = 1;
                            } else {
                                element.status = 2;
                            }
                        });
                        console.log('走', this.data.steps)
                        // this.setData({
                        //     steps: this.data.steps
                        // })
                    }
                    break;


                case 1:
                    if (isInter == 1) {
                        statusBlock = [21, "买家申请小二介入"];
                        this.data.btnList.push({
                            text: "联系客服",
                            type: "contact"
                        }, {
                            text: "撤销申诉",
                            type: "editappeal"
                        },)
                    } else if (isInter == 2) {
                        statusBlock = [22, "小二正在介入"];
                    } else {
                        statusBlock = [1, "审核失败"];
                    }
                    break;
                case 2:

                    statusBlock = [2, "审核成功:待买家发货"];
                    buyerShippedIndex = this.data.steps.findIndex(element => element.text === '买家发货');
                    console.log('buyerShippedIndex', buyerShippedIndex)
                    if (buyerShippedIndex !== -1) {
                        this.data.steps.forEach((element, index) => {
                            if (index <= buyerShippedIndex) {
                                element.status = 1;
                            } else {
                                element.status = 2;
                            }
                        });
                        console.log('走', this.data.steps)
                    }
                    this.setData({
                        sohwMian: true,
                        steps: this.data.steps
                    })
                    break;
                case 3:
                    statusBlock = [3, "买家已发货，等待卖家签收"];
                    buyerShippedIndex = this.data.steps.findIndex(element => element.text === '商家收货');
                    console.log('buyerShippedIndex', buyerShippedIndex)
                    if (buyerShippedIndex !== -1) {
                        this.data.steps.forEach((element, index) => {
                            if (index <= buyerShippedIndex) {
                                element.status = 1;
                            } else {
                                element.status = 2;
                            }
                        });
                        console.log('走', this.data.steps)
                    }
                    this.setData({
                        sohwMian: true,
                        steps: this.data.steps
                    })
                    break;
                case 4:
                    if (isInter == 1) {
                        // this.data.btnList.push({
                        //     text: "联系客服",
                        //     type: "contact"
                        // },{
                        //     text: "撤销申诉",
                        //     type: "editappeal"
                        // }, )
                        statusBlock = [21, "买家申请小二介入"];
                    } else if (isInter == 2) {
                        statusBlock = [22, "小二正在介入"];
                    } else if (refundtype == 2) {
                        // statusBlock = [4, "请退货"];
                        statusBlock = [4, "商家审核不通过"];
                    } else {
                        statusBlock = [4, "卖家拒绝签收"];
                    }
                    break;
                case 5:

                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    }, {
                        text: "撤销申请",
                        type: "remove"
                    }, )
                    buyerShippedIndex = this.data.steps.findIndex(element => element.text === '商家收货');
                    console.log('buyerShippedIndex', buyerShippedIndex)
                    if (buyerShippedIndex !== -1) {
                        this.data.steps.forEach((element, index) => {
                            if (index <= buyerShippedIndex) {
                                element.status = 1;
                            } else {
                                element.status = 2;
                            }
                        });
                        console.log('走', this.data.steps)
                    }
                    statusBlock = [5, "卖家已签收：正等待退款"];
                    this.setData({
                        sohwMian: false,
                    })
                    break;
                case 6:

                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    }, )
                    statusBlock = [6, "已退款"];
                    break;
                case 7:
                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    }, )
                    statusBlock = [7, "买家撤销"];
                    break;
                default:
                    break;
            }
        }
        console.log('===', statusBlock)
        let descTime = this.getRefundStatusText(parseInt(statusBlock[0]), res)
        let data = {
            statusBlock: statusBlock,
            descTime: descTime
        }
        return data;
    },

    getRefundStatusText(status, model) {
        console.log('描述', status, model)
        let timeStr
        let buyerShippedIndex
        // 
        switch (status) {
            case 20:
                this.data.btnList.push({
                    text: "联系客服",
                    type: "contact"
                }, )
                return "退款关闭：退款已关闭";
            case 21:
                // this.data.btnList.push({
                //     text: "联系客服",
                //     type: "contact"
                // },{
                //     text: "撤销申诉",
                //     type: "editappeal"
                // }, )
                return "待小二处理：客服小二处理中";
            case 22:

                return "小二正在处理";
            case 0:
                console.log('``````````````0')
                timeStr = this.countdownTime(model.updatetime, 3);
                console.log('timeStr', timeStr)
                return "待商家处理：商家将在" + timeStr + "内处理";
            case 1:

                this.data.btnList.push({
                    text: "联系客服",
                    type: "contact"
                }, {
                    text: "申诉",
                    type: "appeal"
                }, {
                    text: "撤销申请",
                    type: "remove"
                }, {
                    text: "修改申请",
                    type: "edit"
                }, )
                timeStr = this.countdownTime(model.updatetime, 7);
                // 商家审核不通过：
                return "原因 " + model.verify_error + ",请于" + timeStr + "内修改申请，超时自动取消";
            case 2:
                if (model.refundtype == 1) {
                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    }, )
                    return "审核通过：正等待退款";
                } else {
                    buyerShippedIndex = this.data.steps.findIndex(element => element.text === '填快递单');
                    console.log('buyerShippedIndex', buyerShippedIndex)
                    if (buyerShippedIndex !== -1) {
                        this.data.steps.forEach((element, index) => {
                            if (index <= buyerShippedIndex) {
                                element.status = 1;
                            } else {
                                element.status = 2;
                            }
                        });
                        console.log('走', this.data.steps)
                    }

                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    }, {
                        text: "撤销申请",
                        type: "remove"
                    }, {
                        text: "填快递单",
                        type: "expressBill"
                    })
                    timeStr = this.countdownTime(model.updatetime, 3);
                    return "请于" + timeStr + "内发货并填写快递单，超时自动取消";
                }
                case 3:
                    this.data.btnList.push({
                            text: "联系客服",
                            type: "contact"
                        }, {
                            text: "撤销申请",
                            type: "remove"
                        },
                        //  {
                        //     text: "修改申请",
                        //     type: "edit"
                        // }, 
                    )
                    timeStr = this.countdownTime(model.updatetime, 7);
                    return "待商家收货：商家将在" + timeStr + "内处理";
                case 4:

                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    }, {
                        text: "申诉",
                        type: "appeal"
                    }, {
                        text: "撤销申请",
                        type: "remove"
                    }, {
                        text: "修改快递",
                        type: "exprill"
                    }, )
                    timeStr = this.countdownTime(model.updatetime, 3);
                    return "请退货：商家驳回，原因 " + model.reciever_error
                case 5:
                    return "卖家已签收：正等待退款";
                case 6:

                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    })
                    return "退款总金额：￥" + model.refundprices;
                case 7:

                    this.data.btnList.push({
                        text: "联系客服",
                        type: "contact"
                    })
                    return "退款关闭：您已撤销本次退款申请";
                default:
                    return "退款状态出错啦";
        }
    },
    countdownTime(systemTime, days) {
        // 获取当前时间的时间戳
        let currentTime = new Date().getTime() / 1000;

        // 将系统时间转换为日期对象
        let targetDate = new Date(systemTime * 1000);

        // 在目标日期上增加指定天数
        targetDate.setDate(targetDate.getDate() + days);

        // 计算剩余时间的毫秒数
        let remainingTime = targetDate.getTime() - new Date().getTime();

        // 将毫秒数转换为天、时、分、秒
        let daysLeft = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
        let hoursLeft = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutesLeft = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));

        return daysLeft + "天" + hoursLeft + "时" + minutesLeft + "分";
    },
    /**
     * 退款操作按钮回调函数方法
     * @param {*} e 
     */
    handleSubmit(e) {
        console.log('e', e)
        // 
        if (e.currentTarget.dataset.value.order_state != '0') {

            e.currentTarget.dataset.value.type = e.currentTarget.dataset.value.type = 'refundOnly'
        }
        let type = e.currentTarget.dataset.type
        let data = e.currentTarget.dataset.value
        switch (type) {
            case 'edit':
                // getApp().Tips({
                //     title: "点击了修改申请"
                // })


                wx.navigateTo({
                    url: `/pages/request_refund/index?data=${JSON.stringify(data)}`,
                })
                break;
            case 'remove':
                wx.showModal({
                    title: '温馨提示',
                    content: '确认撤销申请退款么',
                    confirmColor: '#FE3A22',
                    cancelColor: '#1A191E',
                    complete: (res) => {
                        if (res.cancel) {
                            console.log('点击取消按钮');
                        }
                        if (res.confirm) {
                            console.log('点击确认按钮');
                            getNavigationbar({
                                act: 'refund_cancel',
                                id: this.data.dataobj.id || ''
                            }).then(res => {
                                if (res.result == 101) {
                                    wx.showModal({
                                        title: '',
                                        content: res.msg,
                                        showCancel: false, // 是否显示取消按钮，设为false表示不显示
                                        confirmText: '确定', // 确定按钮的文本
                                        success(res) {
                                            if (res.confirm) {
                                                console.log('用户点击确定');

                                            }
                                        }
                                    });
                                } else {
                                    this.getAfterSales(this.data.dataobj);
                                }
                                console.log('撤销退货申请', res);

                            })
                        }
                    }
                })
                break;
            case 'contact':
                wx.makePhoneCall({
                    phoneNumber: "18377766475", //仅为示例，并非真实的电话号码
                    success: function () {
                        console.log("拨打电话成功！");
                    },
                    fail: function () {
                        console.log("拨打电话失败！");
                    },
                });
                break;
            case 'expressBill':
                console.log('this.data.detailsobj', this.data.detailsobj)
                wx.navigateTo({
                    url: `/pages/add_express_numbers/index?data=${JSON.stringify(this.data.detailsobj)}`,
                })
                break;
                case 'exprill':
                    this.data.detailsobj.types = 'et'
                    console.log('this.data.detailsobj', this.data.detailsobj)
                    wx.navigateTo({
                        url: `/pages/add_express_numbers/index?data=${JSON.stringify(this.data.detailsobj)}`,
                    })
                    break;
            case 'appeal':
                wx.navigateTo({
                    url: `/pages/order_appeal/index?data=${JSON.stringify(data)}`
                })
                break;
            case 'editappeal':
                wx.showModal({
                    title: '温馨提示',
                    content: '确认撤销申诉么',
                    confirmColor: '#FE3A22',
                    cancelColor: '#1A191E',
                    complete: (res) => {
                        if (res.cancel) {
                            console.log('点击取消按钮');
                        }
                        if (res.confirm) {
                            console.log('点击确认按钮');
                            getNavigationbar({
                                act: 'appeal_cancel',
                                id: this.data.dataobj.id || ''
                            }).then(res => {
                                console.log('确认撤销申诉么', res);
                                // this.getAfterSales(this.data.dataobj);
                                wx.navigateBack()
                            })
                        }
                    }
                })
                break;

        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            let params = JSON.parse(options.data)
            let data = params.currentTarget.dataset.value
            this.data.dataobj = params.currentTarget.dataset.value
            console.log('进', params)
            this.data.btnList = []
            this.setData({
                navigateName: params.name,
                btnList: this.data.btnList
            })
            wx.nextTick(() => {
                // this.getAfterSales(data);
            })
        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.data.btnList = []
        this.getAfterSales(this.data.dataobj);
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})